package lintulaskenta.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import lintulaskenta.utils.Document;
import lintulaskenta.utils.Document.Node;
import lintulaskenta.utils.TipuApiResource;
import lintulaskenta.validointi.TipuApiValidator;

public class TipuApiForInterface {

    private TipuApiValidator tAV;

    public TipuApiForInterface() throws FileNotFoundException, IOException {
        tAV = new TipuApiValidator();
    }

    // Haetaan kunnat
    public ArrayList getKunnat() throws Exception {
        TipuApiResource kunnat = tAV.kunnat;
        ArrayList<Item> lista = new ArrayList<Item>();
        Iterator<Document.Node> nodeLst = kunnat.getAll().iterator();
        while (nodeLst.hasNext()) {
            Node e = nodeLst.next();
            lista.add(new Item(e.getNode("id").getContents(), e.getNode("name").getContents()));
        }
        return lista;
    }

    // Haetaan rengastajat
    public ArrayList<Item> getRingers() throws Exception {
        TipuApiResource havainnoijat = tAV.havainnoijat;
        ArrayList<Item> lista = new ArrayList<Item>();
        Iterator<Document.Node> nodeLst = havainnoijat.getAll().iterator();

        while (nodeLst.hasNext()) {
            Node e = nodeLst.next();
            String id = e.getNode("id").getContents();
            String firstname = e.getNode("firstname").getContents();
            String lastname = e.getNode("lastname").getContents();
            String name = "";
            if (firstname.length() > 0 && lastname.length() > 0) {
                name = lastname + " " + firstname;
            } else {
                name = lastname + firstname;
            }
            Item havainnoija = new Item(id, name);
            lista.add(havainnoija);
        }
        return lista;

    }
}
